package com.threepure.penpipe.pen;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.util.Log;
import android.view.MotionEvent;

import com.threepure.penpipe.util.Config;

/**
 * @author ThreePure
 * @date 2021/11/17 9:04
 * @description: 橡皮类  通过构造函数设置橡皮擦的宽度
 * @since 1.8
 */
public class Eraser {

    private static final String TAG = "TP_Eraser";

    /**橡皮擦画笔*/
    private Paint eraserPaint;

    /**橡皮擦绘制的路径*/
    private Path path;

    /**记录一个点的坐标*/
    private float lastX;
    private float lastY;

    /**橡皮宽度*/
    private int eraserWidth = Config.eraserSize;

    public Eraser() {
        eraserPaint = new Paint();
        eraserPaint.setStyle(Paint.Style.STROKE);
        eraserPaint.setStrokeJoin(Paint.Join.ROUND);
        eraserPaint.setStrokeCap(Paint.Cap.ROUND);
        eraserPaint.setStrokeWidth(eraserWidth);
        eraserPaint.setFilterBitmap(true);
        eraserPaint.setColor(Color.WHITE);
        eraserPaint.setDither(true);
        eraserPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        eraserPaint.setAntiAlias(true);

        path = new Path();
    }


    /**
     * @description:  橡皮的触摸事件处理
     * @Param: [android.view.MotionEvent, android.graphics.Canvas]
     * @Return: boolean
     */
    public boolean onTouchEvent(MotionEvent event, Canvas canvas){
        //获取当前触摸的坐标轴
        final float x = event.getX();
        final float y = event.getY();
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                lastX = x;
                lastY = y;
                path.reset();
                path.moveTo(x, y);
                break;
            case MotionEvent.ACTION_MOVE:
                // 运用quadTo方法实现二阶 贝塞尔曲线曲线  x1：二次曲线上控制点的x坐标   y1：二次曲线上控制点的y坐标   x2：二次曲线上端点的x坐标   y2：二次曲线上端点的y坐标
                path.quadTo(lastX, lastY, (x + lastX) / 2, (y + lastY) / 2);
                canvas.drawPath(path, eraserPaint);
                lastX = x;
                lastY = y;
                break;
            case MotionEvent.ACTION_UP:
                path.lineTo(lastX, lastY);
                canvas.drawPath(path, eraserPaint);
                break;
            case MotionEvent.ACTION_CANCEL:
            default:
                break;
        }
        return true;
    }

    /**
     * @description: 获取橡皮的宽度
     * @Return: int
     **/
    public int getEraserWidth() {
        return eraserWidth;
    }

    /**
     * @description: 设置橡皮的宽度
     * @param eraserWidth
     * @Return: void
     **/
    public void setEraserWidth(int eraserWidth) {
        this.eraserWidth = eraserWidth;

    }
}
